//
//  PayVIew.swift
//  miaoyin
//
//  Created by David on 2017/3/7.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

@objc protocol PayViewDelegate {
    @objc optional func payView(_ payView: PayView, didSuccessPay data: Any?)
    @objc optional func payView(_ payView: PayView, didCancelPay msg: Any?) ->Bool
}

class PayView: UIView, UITableViewDelegate, UITableViewDataSource {

    var delegate : PayViewDelegate?
    
    private var selIndex = 0
    
    var selectedIndex: Int{
        return selIndex
    }
    
    var closeBtn:UIButton!
    
    var tableView: UITableView!
    
    var price: String?
    var submitBtn: UIButton!
    
    var orderID: String?
    
    var cardView: UIView!
    
    var msgView: UIView!
    var msgImg: UIImageView!
    var msgLabel: UILabel!
    
    var successImg: UIImageView!
    
    var loadingView: LLFullScreenLoading!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let bgView = UIVisualEffectView(frame: frame)
        bgView.effect = UIBlurEffect(style: .dark)
        addSubview(bgView)
        
        successImg = UIImageView(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
        successImg.center = CGPoint(x: frame.width/2, y: frame.height/2)
        successImg.image = #imageLiteral(resourceName: "finish")
        bgView.addSubview(successImg)
        
        cardView = UIView(frame: CGRect(x: 16, y: 0, width: frame.width - 32, height: CGFloat(Fatcat.payMethods.count+3)*44))
        cardView.center = CGPoint(x: frame.width/2, y: frame.height/2)
        cardView.backgroundColor = UIColor.white
        cardView.layer.cornerRadius = 8
        bgView.addSubview(cardView)
        
        let titleBar = UIView(frame: CGRect(x: 0, y: 0, width: cardView.frame.width, height: 44))
        cardView.addSubview(titleBar)
        
        closeBtn = UIButton(frame: CGRect(x: 16, y: 0, width: 44, height: 44))
        closeBtn.setTitle("×", for: .normal)
        closeBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24)
        closeBtn.setTitleColor(themeColor2, for: .normal)
        titleBar.addSubview(closeBtn)
        closeBtn.addTarget(self, action: #selector(PayView.closeView), for: .touchUpInside)
        
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: cardView.frame.width - (16+44)*2, height: 44))
        titleLabel.center.x = cardView.frame.width/2
        titleLabel.text = "选择支付方式"
        titleLabel.textAlignment = .center
        titleBar.addSubview(titleLabel)
        
        tableView = UITableView(frame: CGRect(x: 0, y: 66, width: cardView.frame.width, height: CGFloat(Fatcat.payMethods.count)*44))
        tableView.delegate = self
        tableView.dataSource = self
        cardView.addSubview(tableView)
        
        submitBtn = UIButton(frame: CGRect(x: 16, y: cardView.frame.height-52, width: cardView.frame.width-32, height: 44))
        submitBtn.layer.cornerRadius = 8
        submitBtn.backgroundColor = themeColor1
        submitBtn.setTitle("立即支付", for: .normal)
        submitBtn.setTitleColor(UIColor.white, for: .normal)
        cardView.addSubview(submitBtn)
        submitBtn.addTarget(self, action: #selector(PayView.doPayment), for: .touchUpInside)
        
        alpha = 0
        
        loadingView = LLFullScreenLoading(frame: frame)
        addSubview(loadingView)
        loadingView.alpha = 0
        
        msgView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        msgView.center = CGPoint(x: frame.width/2, y: frame.height/2)
        msgView.backgroundColor = UIColor(white: 0, alpha: 0.6)
        msgView.layer.cornerRadius = 8
        
        msgImg = UIImageView(frame: CGRect(x: 0, y: 0, width: 48, height: 48))
        msgImg.center = CGPoint(x: 50, y: 40)
        msgView.addSubview(msgImg)
        msgImg.image = #imageLiteral(resourceName: "warning")
        
        msgLabel = UILabel(frame: CGRect(x: 0, y: 72, width: 100, height: 20))
        msgLabel.font = UIFont.systemFont(ofSize: 14)
        msgLabel.textColor = UIColor.white
        msgLabel.text = "支付失败"
        msgLabel.textAlignment = .center
        msgView.addSubview(msgLabel)
        
        addSubview(msgView)
        msgView.alpha = 0
    }
    
    func openView(_ price: String?, orderID: String?){
        selIndex = 0
        tableView.reloadData()
        self.price = price
        self.orderID = orderID
        submitBtn.setTitle("立即支付 ￥\(price ?? "0.00")", for: .normal)
        submitBtn.isEnabled = true
        closeBtn.isEnabled = true
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 1
        })
        
        msgView.alpha = 0
        msgLabel.text = "支付失败"
        msgImg.image = #imageLiteral(resourceName: "warning")
        
    }
    
    func closeView(){
        let close = delegate?.payView?(self, didCancelPay: nil)
        if close != nil {
            if !close! {
                return
            }
        }
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        })
    }
    
    func doPayment(){
        
        if orderID != nil && price != nil{
            let priceAmount = Double(price!)
            if priceAmount != nil{
                if Int(priceAmount!*100) != 0{
                    print("go \(orderID!) pay \(price!)")
                    
                    var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=goods&a=payOrder")!)
                    resq.httpMethod = "POST"
                    resq.httpBody = "or_num=\(orderID!)".data(using: .utf8)//&total_amount=\(price!)
                    
                    loadingView.alpha = 1
                    self.submitBtn.isEnabled = false
                    URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, re:URLResponse?, err:Error?) in
                        DispatchQueue.main.async {
                            self.loadingView.alpha = 0
                        }
                        do{
                            if err != nil{
                                throw err!
                            }
                            
                            var info = String(data: data!, encoding: .utf8)
//                            var baseData = Data(base64Encoded: data!)
                            
//                            info = info?.removingPercentEncoding
                            info = info?.replacingOccurrences(of: "&amp;", with: "&")
//                            info = info?.replacingOccurrences(of: "+\"", with: "\"")
//                            info = info?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlUserAllowed)
                            
                            
//                            info = info?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)
                            print(info ?? "data nil")
                            
                            if info != nil{
//                                let ordStr = "app_id=2015052600090779&biz_content={\"timeout_express\":\"30m\",\"seller_id\":\"\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"0.01\",\"subject\":\"1\",\"body\":\"我是测试数据\",\"out_trade_no\":\"IQJZSRC1YMQB5HU\"}&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=http://domain.merchant.com/payment_notify&sign_type=RSA2&timestamp=2016-08-25 20:26:31&version=1.0&sign=cYmuUnKi5QdBsoZEAbMXVMmRWjsuUj+y48A2DvWAVVBuYkiBj13CFDHu2vZQvmOfkjE0YqCUQE04kqm9Xg3tIX8tPeIGIFtsIy"
                                
                                UserDefaults.standard.set(self.price!, forKey: orderToDoPrice)
                                UserDefaults.standard.set(self.orderID!, forKey: orderToDoID)
                                (UIApplication.shared.delegate as? AppDelegate)?.payView = self
                                
                                AlipaySDK.defaultService().payOrder(info!, fromScheme: "miaoyin", callback: { (resultDic) in
                                    print("payView:")
                                    print(resultDic ?? "result nil")
                                    
                                    DispatchQueue.main.async {
                                        self.paymentResult(resultDic)
                                    }
                                    
                                    
                                    
                                })
                            }else{
                                DispatchQueue.main.async {
                                    self.showFailedMsg()
                                }
                            }
                            
                            
                            
                            
                            
                        }catch let ex{
                            DispatchQueue.main.async {
                                self.showFailedMsg()
                            }
                            print(ex)
                        }
                    }).resume()
                }
            }
        }
    }
    
    func paymentResult(_ result: [AnyHashable: Any]?){
        
        submitBtn.isEnabled = true
        
        if result == nil{
            showFailedMsg()
            return
        }
        
        let resultStr = result!["result"] as? String
        
        if resultStr == nil{
            showFailedMsg()
            return
        }
        
        if resultStr == "" {
            showFailedMsg()
            return
        }
        
        paySuccess()
        
    }
    
    func showFailedMsg(){
        msgView.alpha = 0
        UIView.animate(withDuration: 0.3, animations: {
            self.msgView.alpha = 1
        }, completion: { (finish) in
            UIView.animate(withDuration: 0.3, delay: 2, options: .curveLinear, animations: {
                self.msgView.alpha = 0
            }, completion: nil)
        })
    }
    
    func paySuccess(){
        submitBtn.isEnabled = false
        closeBtn.isEnabled = false
        msgImg.image = #imageLiteral(resourceName: "finish")
        msgLabel.text = "支付成功"
        
        msgView.alpha = 0
        UIView.animate(withDuration: 0.3, animations: {
            self.msgView.alpha = 1
        }, completion: { (finish) in
            UIView.animate(withDuration: 0.3, delay: 2, options: .curveLinear, animations: {
                self.msgView.alpha = 0
            }, completion: {(fin) in
                self.delegate?.payView?(self, didSuccessPay: nil)
                UIView.animate(withDuration: 0.3, animations: {
                    self.alpha = 0
                })
            })
        })
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Fatcat.payMethods.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "pay")
        if selIndex == indexPath.row{
            cell.accessoryType = .checkmark
        }else{
            cell.accessoryType = .none
        }
        
        let iconView = UIImageView(frame: CGRect(x: 16, y: 8, width: 28, height: 28))
        iconView.backgroundColor = UIColor.lightGray
        iconView.layer.cornerRadius = 4
        cell.addSubview(iconView)
        iconView.image = UIImage(named: Fatcat.payMethods[indexPath.row]["id"]!)
        
        let titleLabel = UILabel(frame: CGRect(x: 52, y: 8, width: frame.width - 128, height: 28))
        titleLabel.font = UIFont.systemFont(ofSize: 14)
        titleLabel.text = Fatcat.payMethods[indexPath.row]["name"]
        cell.addSubview(titleLabel)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selIndex = indexPath.row
        tableView.deselectRow(at: indexPath, animated: true)
        
        tableView.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .automatic)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
